const express = require('express')
const bodyParser = require('body-parser')
const model = require('./db/models')
const todo = model.todo
const app = express()
app.use(express.json())
app.use(express.urlencoded())
app.use(bodyParser.urlencoded({extended: true}))
app.get('/list', async (req, res, next) => {
	try {
		let datam = {...req.query}
		let limit = parseInt(datam.pagesize)
		let offset = datam.pagesize * (datam.pagenum - 1)
		const ret = {
			code: 200,
			msg: ''
		}
		let data = await todo.findAll({
			offset,
			limit
		})
		let total = await todo.findAll()
		ret.data = data
		ret.msg = '获取待办列表成功!'
		ret.total = total.length
		res.json({...ret})
	} catch (e) {
		next(e)
	}
})

app.post('/create', async (req, res,next) => {
	const rett = {
		code: 200,
		msg: ''
	}
	try {
		let {id,name, deadtime, content, status, pagesize, pagenum} = req.body
		let onething = await todo.findOne({
			where: {
				id
			}
		})
		if (!onething) {
			let ret = await todo.create({
				name,
				deadtime,
				content,
				status
			})
			rett.msg = '事件创建成功!'
		} else {
			let  ret = await onething.update({
				name,
				deadtime,
				content,
				status
			})
			rett.msg = '事件修改成功!'
		}
		let data = await todo.findAll()
		rett.total = data.length
		req.body.rett = rett
		next()
	} catch (e) {
		next(e)
	}
})

app.post('/delete', async (req, res,next) => {
	let {id,status,pagesize, pagenum} = req.body
	let onthing = await todo.findOne({
		where:{
			id
		}
	})
	let oo = await onthing.update({
		status
	})
	const rett = {
		code: 200,
		msg: '删除成功'
	}
	let data = await todo.findAll()
	rett.total = data.length
	req.body.rett = rett
	next()
})
let list = async (req,res,next) => {
	let {pagesize, pagenum, rett} = req.body
	let limit = pagesize
	let offset = pagesize * (pagenum - 1)
	let data = await todo.findAll({
		offset,
		limit
	})
	rett.data = data
	res.json({...rett})
}

app.use(list)
app.use((erro,req,res,next) => {
	if(erro) {
		res.status(500).json({
			message: erro.message
		})
	}
})
app.listen(3000, ()=> {
	console.log('服务已经启动,端口3000')
})
